/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: zhaosj
 * Date: 2011-5-4 上午10:39:01
 */
package com.dom4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


/**
 * @author zhaosj
 * 
 */
public class XMLPaser {

	/**
	 * 解析各节点
	 * 
	 * @param originalXMLStr
	 * @return
	 */
	public String getSecuritiesListByCategory(String originalXMLStr) {

		Element root = this.getRootElement(originalXMLStr);
		
		JSONArray jsonArray = new JSONArray();
		for (Iterator i = root.elementIterator(); i.hasNext();) {
			Element ele = (Element) i.next();
			if (ele.getName().equals("bond")) 
			{
				int k = 0;
				SecuritiesVO sv = new SecuritiesVO();
				String aStrVar = "";
				for (Iterator j = ele.elementIterator(); j.hasNext(); k++) {
					Element el = (Element) j.next();
					aStrVar = el.getText();
					switch (k) {
					case 0:
						sv.setCode(aStrVar);
						break;
					case 1:
						sv.setName(aStrVar);
						break;
					case 2:
						sv.setInnerCode(aStrVar);
						break;
					default:

					}
				}
				jsonArray.add(sv);
			}
		}

		return jsonArray.toString();
	}

	/**
	 * ORACLE CLOB 转换为String
	 * 
	 * @param clob
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public static String ClobToStr(oracle.sql.CLOB clob) throws SQLException, IOException {
		Reader reader = clob.getCharacterStream();
		BufferedReader br = new BufferedReader(reader);
		String str = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (str != null) {
			sb.append(str);
			str = br.readLine();
		}
		return sb.toString();
	}

	/**
	 * 调用远程URL获取文本
	 * 
	 * @param remoteUrl
	 * @return
	 */
	private String getRemoteData(String remoteUrl) {
		String data = "";
		try {
			URL url = new URL(remoteUrl);
			URLConnection con = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

			String line = "";
			while ((line = in.readLine()) != null) {
				data += line;
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return data;
	}

	public String getTreeByRemote(String url) {
		String JSONString = "";
		String xmlText = this.getRemoteData(url);
		Element element = this.getRootElement(xmlText);
		List<Element> list = this.getAllNode(element);
		JSONString = this.parseJSON(list);

		return JSONString;
	}

	private String parseJSON(List<Element> list) {
		JSONArray jsonArray = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			Element e = (Element) list.get(i);
			PlateTreeVO pt = new PlateTreeVO();
			pt.setNode_id(e.attribute("id").getData().toString());
			pt.setNode_parent_id(e.getParent().attribute("id").getData().toString());
			pt.setNode_name(e.attribute("text").getData().toString());

			jsonArray.add(pt);
		}

		return jsonArray.toString();
	}

	private Element getRootElement(String xmlText) {
		Element root = null;
		try {
			Document document = DocumentHelper.parseText(xmlText);
			root = document.getRootElement();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return root;
	}

	private List<Element> getAllNode(Element element) {
		List<Element> allElement = new ArrayList<Element>();

		List<Element> e_list = element.elements(); // 得到当前对象的第一级子节点的集合
		if (e_list != null && e_list.size() >= 1) { // 如果element对象没有子节点，那么e_list将会是一个null
			for (int i = 0; i < e_list.size(); i++) {
				Element e = (Element) e_list.get(i);
				allElement.add(e); // 将循环出来的Element对象保存到大集合
				List<Element> e_sonList = this.getAllNode(e);
				if (e_sonList != null && e_sonList.size() >= 1) { // 跟上面的if过滤性质一样
					for (int j = 0; j < e_sonList.size(); j++) {
						Element e_son = e_sonList.get(j);
						allElement.add(e_son);
					}
				}
			}
		}

		return allElement;
	}

	private String parseXml(String xmlText) {
		String aStringVar = null;
		try {
			Document document = DocumentHelper.parseText(xmlText);
			List list = document.selectNodes("//bond");
			Iterator iter = list.iterator();
			while (iter.hasNext()) {
				Element element = (Element) iter.next();
				Iterator iterator = element.elementIterator("value");
				while (iterator.hasNext()) {
					Element titleElement = (Element) iterator.next();
					if (titleElement.getText().equals("Java configuration with XML Schema"))
						titleElement.setText("Create flexible and extensible XML schema");
				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

		return aStringVar;

	}

	public static void main(String[] args) {

		String example = "<bonds><bond><value>000001</value><value>深发展Ａ</value><valueinnercode>101000912</valueinnercode></bond><bond><value>000002</value><value>万 科Ａ</value><valueinnercode>101000783</valueinnercode></bond></bonds>";
		// String url = "http://10.0.3.173:8080/ccxe/servlet/FilterLimitTreeServlet?system=2&module=2&option=initTree&useByThirdPart=1";
		String url = "http://10.0.3.173:8080/ccxe/servlet/LimitAjax?system=2&module=2&option=searchCrossBonds&isContainOldSecu=true&useByThirdPart=1&limitString=210001";

		XMLPaser xp = new XMLPaser();
		// String content = xp.getTreeByRemote(url);
		String content = xp.getRemoteData(url);
		System.out.println(content);

		content = xp.getSecuritiesListByCategory(content);

		// content = content.substring(0, content.indexOf("<pager")) + content.substring(content.indexOf("</bonds>"));
		System.out.println(content);
	}

}
